package com.jin.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jin.Exception.http.ParameterException;
import com.jin.model.User;
import com.jin.repository.UserRepository;
import com.jin.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class WxAuthenticationService {
    @Autowired
    ObjectMapper mapper;
    @Autowired
    UserRepository userRepository;

    //把配置文件的数据注入进来
    @Value("${wx.code2session}")
    private String code2SessionUrl;
    @Value("${wx.appid}")
    private String appId;
    @Value("${wx.appsecret}")
    private String appSecret;

    //根据小程序给的code码来决定是不是要返还给token
    public String code2Session(String code){
        //拼接字符串的方法，第一个参数是模板字符串，剩下的是三个参数
        String url = MessageFormat.format(code2SessionUrl,appId,appSecret,code);
        System.out.println(url);
        //调用服务器
        RestTemplate rest = new RestTemplate();
        Map<String,Object> session = new HashMap<>();
        //返回值类型(请求这个url之后返回的类型),sessionTest是请求之后的返回结果
        String sessionTest = rest.getForObject(url, String.class);
        //把结果反序列成对象
        try {
            session = mapper.readValue(sessionTest, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return registerUser(session);
    }

    //拿到openId
    private String registerUser(Map<String,Object> session){
        String openId = (String) session.get("openid");
        if (openId==null){
            throw new ParameterException(20004);
        }
       User user = userRepository.findByOpenid(openId);
        //注册
        if (user==null){
            User userInfo = User.builder().openid(openId).build();
            //把user写入到数据库中
            userRepository.save(userInfo);
            //写入之后返回JWT令牌
            return JwtToken.makeToken(userInfo.getId());
        }
        else {
            //生成令牌
            return JwtToken.makeToken(user.getId());
        }


    }
}
